package com.gxa.learning.pc.service.impl;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.LevelManager;
import com.gxa.learning.core.pojo.TypeLevelManagerVO;
import com.gxa.learning.core.service.impl.BaseServiceImpl;
import com.gxa.learning.core.util.ExcelUtils;
import com.gxa.learning.core.util.OssUtil;
import com.gxa.learning.pc.mapper.LevelManagerMapper;
import com.gxa.learning.pc.service.LevelManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author lijianmin
 * @date 2021/12/03  15:44:13
 */
@Service("levelManagerService")
@Transactional(rollbackFor = {Throwable.class}, propagation = Propagation.REQUIRED)
public class LevelManagerServiceImpl extends BaseServiceImpl<LevelManager> implements LevelManagerService {

    @Resource
    private LevelManagerMapper levelManagerMapper;

    @Autowired
    private HttpServletRequest request;

    /**
     * 根据条件搜索的方法(如果条件为空 则为全查询, 如果不传分页条件,则默认为第1页10条数据)
     *
     * @param typeName         类别名称
     * @param level            类别等级
     * @param state            每页数据量
     * @param uploadPeopleName 上传人
     * @param page             页码
     * @param size             每页数据量
     * @return 返回数据以及分页等信息
     */
    @Override
    public PageInfo<TypeLevelManagerVO> selectByLike(String typeName, String level, Integer state, String uploadPeopleName, Integer page, Integer size) throws BusinessException {
        if (page == null || size == null) {
            page = 1;
            size = 10;
        }
        if (page < 1 || size < 1) {
            throw new BusinessException(ExceptionCode.PAGE_SIZE_ERROR);
        }
        PageMethod.startPage(page, size);
        List<TypeLevelManagerVO> list = levelManagerMapper.selectByLike(typeName, level, state, uploadPeopleName);
        return PageInfo.of(list);
    }

    /**
     * 根据类别id、等级、状态查询是否存在满足条件的数据
     *
     * @param levelManager 条件
     * @throws BusinessException 操作中产生的异常
     */
    @Override
    public void selectExist(LevelManager levelManager) throws BusinessException {

        LevelManager levelManager1 = levelManagerMapper.selectExist(levelManager.getLevel(), levelManager.getTypeId(), levelManager.getState());
        if (levelManager1 != null) {
            if (levelManager1.getId() != null) {
                throw new BusinessException(ExceptionCode.TYPE_LEVEL_EXIST);
            }
        }
    }

    /**
     * 批量导入等级的方法
     *
     * @param multipartFile 文件对象
     * @throws Exception 操作中产生的异常
     */
    @Override
    public void batchAdd(MultipartFile multipartFile) throws Exception {
        // 1.---------上传文件----
        String originalFilename = multipartFile.getOriginalFilename();
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String suffix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        // 使用UUID作为文件名,保证服务器中存放的文件名唯一
        String targetFile = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        // 获得云上该文件地址
        String fileName = "https://bucket-yanxiaoqi.oss-cn-chengdu.aliyuncs.com/learning/excel/" + targetFile;
        // 构建文件对象
        InputStream inputStream = multipartFile.getInputStream();
        // 上传到OSS
        OssUtil.upload(fileName, inputStream);
        // 上传结束后 会关闭流对象 所以再次打开流对象
        InputStream inputStreams = multipartFile.getInputStream();
        //通过ExcelUtils工具类将文件转换为集合
        List<List<Object>> list = ExcelUtils.getListByExcel(inputStreams, fileName);
        //遍历集合 将数据添加到LevelManager对象
        for (int i = 0; i < list.size(); i++) {
            LevelManager levelManager = new LevelManager();
            for (int i1 = 0; i1 < list.get(i).size(); i1++) {
                if (i1 == 0) {
                    levelManager.setLevel(list.get(i).get(i1).toString());
                } else if (i1 == 1) {
                    levelManager.setTypeId(Long.valueOf(list.get(i).get(i1).toString()));
                } else if (i1 == 2) {
                    levelManager.setState(Integer.valueOf(list.get(i).get(i1).toString()));
                } else if (i1 == 3) {
                    levelManager.setUploadPeople(Long.valueOf(list.get(i).get(i1).toString()));
                }
            }
            //进行判断,数据库中是否存在了相同的记录
            selectExist(levelManager);
            // 进行添加操作
            LevelManager insert = super.insert(levelManager);
            //如果添加的某一次为空则抛异常进行回滚
            if (insert == null) {
                throw new BusinessException(ExceptionCode.FAILED_OPTION);
            }
        }
    }

}
